package com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dao.*;
import com.pojo.Chat;
import com.pojo.Chatdetail;
import com.pojo.Kefu;
import com.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Author: ttw
 * @Date: 2021-10-11
 * @Description: 客服与用户的聊天信息处理
 */
@Service
public class ChatService extends ServiceImpl<ChatDAO, Chat> {

    @Autowired
    private ChatDAO chatDAO;
    @Autowired
    private ChatdetailDAO chatdetailDAO;
    @Autowired
    private UsersDAO usersDAO;
    @Autowired
    private KefuDAO kefuDAO;

    /**
     * 新增一个客服与用户的关系
     *
     * @param kefuName 客服名
     * @param userName 用户名
     * @return
     */
    public String addChat(String kefuName, String userName) {
        if (userName==null){
            return "用户名为null";
        }
        //前缀为user的用户设置为游客用户
        if (userName.startsWith("user")){
            if (usersDAO.selectOne(new QueryWrapper<Users>().eq("utel",userName).last("limit 1"))==null){
                Users users = new Users();
                users.setUtel(userName);
                users.setUname(userName);
                users.setUstatus(1);
                users.setType(2);
                int n = usersDAO.insert(users);
                if (n<=0){
                    return "新增游客用户失败";
                }
            }
        }
        List<Chat> chatList = chatDAO.selectList(new QueryWrapper<Chat>().eq("userName", userName).eq("kefuName", kefuName));
        if (chatList.size() > 0) {
            return null;
        }
        Chat chat = new Chat();
        chat.setKefuName(kefuName);
        chat.setUserName(userName);
        int n = chatDAO.insert(chat);
        if (n > 0) {
            return null;
        } else {
            return "新增失败";
        }
    }

    /**
     * 用户打开连接，系统发一句 我是客服。。。給用户
     *
     * @param kefuName 客服名
     * @param userName 用户名
     * @return
     */
    public String iAmKefu(String kefuName, String userName) {
        Chat chat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("kefuName", kefuName).eq("userName", userName).last("limit 1"));
        Users users = usersDAO.selectOne(new QueryWrapper<Users>().eq("utel",userName).last("limit 1"));
        if (chat != null) {
            if (users !=null){
                Chatdetail chatdetail = new Chatdetail();
                chatdetail.setStatus(1);
                chatdetail.setTime(new Date());
                chatdetail.setChatId(chat.getId());
                chatdetail.setKefumsg("我是客服：" + kefuName);
                chatdetail.setMtype(3);
                chatdetail.setKname(kefuName);
                chatdetail.setUname(users.getUname());
                if (chatdetailDAO.insert(chatdetail) > 0) {
                    return null;
                } else {
                    return "新增失败";
                }
            }else{
                return "未找到用户";
            }
        } else {
            return "未找到";
        }
    }

    /**
     * 存储发送的消息内容
     *
     * @param sendname    发消息的人
     * @param receivename 接收消息的人
     * @param msg         消息内容
     * @param type        类型，1：表示用户发给客服 2：表示客服发给用户
     * @return
     */
    public String addChatDetail(String sendname, String receivename, Object msg, int type,int ptype) {
        Chat chat = null;
        Users users = null;
        if (type == 1) {
            chat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("userName", sendname).eq("kefuName", receivename).last("limit 1"));
            users = usersDAO.selectOne(new QueryWrapper<Users>().eq("utel",sendname).last("limit 1"));
        } else {
            chat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("userName", receivename).eq("kefuName", sendname).last("limit 1"));
            users = usersDAO.selectOne(new QueryWrapper<Users>().eq("utel",receivename).last("limit 1"));
        }
        Chatdetail chatdetail = new Chatdetail();
        if(chat==null){
            chat = new Chat();
            if (type == 1){
                chat.setUserName(sendname);
                chat.setKefuName(receivename);
            }else{
                chat.setUserName(receivename);
                chat.setKefuName(sendname);
            }
            chatDAO.insert(chat);
        }
        if (chat != null) {
            if (users != null){
                if (ptype==1){
                    if (type == 1) {//用户发给客服
                        chatdetail.setUsermsg((String) msg);
                        chatdetail.setStatus(0);
                        chatdetail.setUseStatus(1);
                    } else {//客服发给用户
                        chatdetail.setKefumsg((String) msg);
                        chatdetail.setStatus(1);
                        chatdetail.setUseStatus(0);
                    }
                }else{
                    if (type == 1) {//用户发给客服
                        chatdetail.setPicture((String) msg);
                        chatdetail.setStatus(0);
                        chatdetail.setUseStatus(1);
                    } else {//客服发给用户
                        chatdetail.setPicture((String) msg);
                        chatdetail.setStatus(1);
                        chatdetail.setUseStatus(0);
                    }
                }
                chatdetail.setPtype(ptype);
                chatdetail.setMtype(type);
                chatdetail.setChatId(chat.getId());
                chatdetail.setTime(new Date());
                if (type == 1){
                    chatdetail.setKname(receivename);
                }else{
                    chatdetail.setKname(sendname);
                }
                chatdetail.setUname(users.getUname());

                if (chatdetailDAO.insert(chatdetail) > 0) {
                    return null;
                } else {
                    return "新增失败";
                }
            }else{
                return "未找到用户";
            }
        } else {
            return "请重新打开聊天";
        }
    }

    /**
     * 根据客服名和用户名加载历史聊天记录
     *
     * @param kefuname 客服名
     * @param username 用户名
     * @return
     */
    public List<Chatdetail> getHistoryChat(String kefuname, String username) {
        //先判断该用户与客服是否已建立联系
        Chat chat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("kefuName", kefuname).eq("userName", username).last("limit 1"));
        List<Chatdetail> chatdetailList = new ArrayList<>();
        if (chat != null) {
            QueryWrapper<Chatdetail> qw = new QueryWrapper<>();
            qw.eq("chatId", chat.getId());
            qw.orderByAsc("time");
            chatdetailList = chatdetailDAO.selectList(qw);
            UpdateWrapper<Chatdetail> upd = new UpdateWrapper();
            Chatdetail chatdetail = new Chatdetail();
            upd.in("chatId", chat.getId());
            upd.set("status", 1);
            chatdetailDAO.update(chatdetail, upd);
            return chatdetailList;
        } else {
            return chatdetailList;
        }
    }

    /**
     * 根据用户名获取该用户所有的历史记录
     *
     * @param username 用户名
     * @return
     */
    public List<Chatdetail> getHistoryUser(String username) {
        List<Chat> chatList = chatDAO.selectList(new QueryWrapper<Chat>().eq("userName", username));
        List<String> usernameList = new ArrayList<>();
        List<Chatdetail> chatdetailList = new ArrayList<>();
        if (chatList.size() > 0) {
            for (Chat chat : chatList) {
                usernameList.add(chat.getId());
            }
            QueryWrapper<Chatdetail> qw = new QueryWrapper<>();
            qw.in("chatId", usernameList);
            qw.orderByAsc("time");
            chatdetailList = chatdetailDAO.selectList(qw);
            return chatdetailList;
        } else {
            return chatdetailList;
        }
    }

    /**
     * 根据客服名，查询该客服所有的聊天用户
     *
     * @param kefuname 客服名
     * @return
     */
    public IPage getChatForUser(String kefuname, int page, int limit) {
        Page p = new Page(page, limit);
        QueryWrapper<Chat> qw = new QueryWrapper<>();
        qw.eq("kefuName", kefuname);
        IPage iPage = chatDAO.getZuijinChat(p, kefuname);
        return iPage;
    }

    /**
     * 加载客服与这位用户的未读消息
     *
     * @param kefuname 客服名
     * @param username 用户名
     * @return
     */
    public List<Chatdetail> addnewChat(String kefuname, String username) {
        //先判断该用户与客服是否已建立联系
        Chat chat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("kefuName", kefuname).eq("userName", username).last("limit 1"));
        List<Chatdetail> chatdetailList = new ArrayList<>();
        if (chat != null) {
            QueryWrapper<Chatdetail> qw = new QueryWrapper<>();
            qw.eq("chatId", chat.getId());
            qw.eq("status", 0);
            qw.orderByAsc("time");
            chatdetailList = chatdetailDAO.selectList(qw);
            UpdateWrapper<Chatdetail> upd = new UpdateWrapper();
            Chatdetail chatdetail = new Chatdetail();
            upd.in("chatId", chat.getId());
            upd.set("status", 1);
            chatdetailDAO.update(chatdetail, upd);
            return chatdetailList;
        } else {
            return chatdetailList;
        }
    }

    /**
     * 当没有客服在线时，给某个客服发消息存入数据库。
     * @param username 用户手机号
     * @param message 消息的内容
     * @param ptype 1：文字 2：图片
     * @param areaId 区域id
     * @return
     */
    public String addMessageWhenNotKefu(String username,String message,int ptype,String areaId){
        String uname =username;
        if (username.startsWith("+")){
            Users users = usersDAO.selectOne(new QueryWrapper<Users>().eq("utel",username).last("limit 1"));
            if (users!=null){
                uname=users.getUname();
            }
        }
        Chat chatRecent = chatDAO.getChat(username,areaId);//获取最近和该用户聊天的同区域的客服
        Chatdetail chatdetail=new Chatdetail();
        if (chatRecent!=null){
            if (ptype==1){
                chatdetail.setUsermsg(message);
                chatdetail.setPtype(1);
            }else{
                chatdetail.setPicture(message);
                chatdetail.setPtype(2);
            }
            chatdetail.setChatId(chatRecent.getId());
            chatdetail.setKname(chatRecent.getKefuName());
            chatdetail.setUname(uname);
            chatdetail.setMtype(1);
            chatdetail.setStatus(0);
            chatdetail.setUseStatus(1);
            chatdetail.setTime(new Date());
            chatdetailDAO.insert(chatdetail);
            return null;
        }else{//如果没有则找其他同区域的客服
            Kefu kefuNotChat = kefuDAO.selectOne(new QueryWrapper<Kefu>().eq("status",1).eq("areaId",areaId).last("limit 1"));
            if (kefuNotChat!=null){
                Chat newchat = chatDAO.selectOne(new QueryWrapper<Chat>().eq("kefuName",kefuNotChat.getKefuName()).eq("userName",username).last("limit 1"));
                if (newchat==null){
                    //先建立客服和用户的关系
                    newchat = new Chat();
                    newchat.setKefuName(kefuNotChat.getKefuName());
                    newchat.setUserName(username);
                    chatDAO.insert(newchat);
                }
                if (ptype==1){
                    chatdetail.setUsermsg(message);
                    chatdetail.setPtype(1);
                }else{
                    chatdetail.setPicture(message);
                    chatdetail.setPtype(2);
                }
                chatdetail.setChatId(newchat.getId());
                chatdetail.setKname(newchat.getKefuName());
                chatdetail.setUname(uname);
                chatdetail.setMtype(1);
                chatdetail.setStatus(0);
                chatdetail.setUseStatus(1);
                chatdetail.setTime(new Date());
                chatdetailDAO.insert(chatdetail);
                return null;
            }else{
                return "当前没有可用客服";
            }
        }
    }

    /**
     * 获取用户的未读消息数
     * @param username 用户名
     * @return
     */
    public int getUserHintNumber(String username){
        int n = chatdetailDAO.selectCount(new QueryWrapper<Chatdetail>().eq("uname",username).eq("useStatus",0));
        return n ;
    }

}
